package com.yyg.usecase.springbootwebdemo.oom_cpu_case;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Objects;
import java.util.concurrent.ExecutorService;

@Component
public class CpuOomSimulationService {

    @Autowired
    private ExecutorService queryExecutor;

    //duration 单位为s
    public void Cpu100Simulation(int duration) {
        long start = System.currentTimeMillis();
        // 模拟CPU占用100%的情况
        while (true) {
            if (System.currentTimeMillis() - start > duration * 1000L) {
                break;
            }
        }
    }

    //内存gc
    public void MemoryOomSimulation(int taskNum, int taskMem /*MB*/, int taskDuration /*ms*/,
                                    Integer taskDelay /*ms*/) {
        for (int i = 0; i < taskNum; i++) {
            Runnable task = () -> {
                try {
                    byte[] needMem = new byte[taskMem * 1024 * 1024];
                    Thread.sleep(taskDuration);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            };
            queryExecutor.execute(task);
            if (Objects.nonNull(taskDelay) && taskDelay > 0) {
                try {
                    Thread.sleep(taskDelay);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }


    public void systemGc() {
        System.gc();
    }


}
